<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'

// 定义组件接收的属性
interface Props {
  type?: 'success' | 'error' | 'info'
  message: string
  duration?: number
  onClose?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  type: 'info',
  duration: 3000,
  onClose: () => {},
})

const visible = ref(false)
let timer: number | null = null

// 组件挂载时显示消息
onMounted(() => {
  visible.value = true

  // 设置定时器，自动关闭消息
  timer = setTimeout(() => {
    close()
  }, props.duration)
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearTimeout(timer)
  }
})

// 关闭消息
function close() {
  visible.value = false
  setTimeout(() => {
    props.onClose()
  }, 300) // 等待动画结束后调用关闭回调
}
</script>

<template>
  <transition name="message-fade">
    <div v-if="visible" class="message" :class="[`message--${type}`]">
      <span class="message__content">{{ message }}</span>
    </div>
  </transition>
</template>

<style scoped>
.message {
  width: 300px;
  max-width: 80vw;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message--success {
  background-color: var(--success-color-100);
  border-left: 4px solid var(--success-color);
  color: var(--success-color);
}

.message--error {
  background-color: var(--danger-color-100);
  border-left: 4px solid var(--danger-color);
  color: var(--danger-color);
}

.message--info {
  background-color: var(--primary-color-100);
  border-left: 4px solid var(--primary-color);
  color: var(--primary-color);
}

.message__content {
  font-size: 14px;
  line-height: 1.5;
}

/* 动画效果 */
.message-fade-enter-active,
.message-fade-leave-active {
  transition:
    opacity 0.3s,
    transform 0.3s;
}

.message-fade-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.message-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
